import re
import os
import utils
import collect
from openpyxl.utils import get_column_letter
from openpyxl.styles import PatternFill, Border, Side, Alignment

fill_date = PatternFill(
    fill_type='solid', start_color='D9FDE900', end_color='D9FDE900')
fill_main = PatternFill(
    fill_type='solid', start_color='C6FDCC00', end_color='C6FDCC00')
fill_alt = PatternFill(
    fill_type='solid', start_color='BCD7E400', end_color='BCD7E400')

thin = Side(border_style="thin", color="000000")
border_normal = Border(top=thin, bottom=thin, left=thin, right=thin)
align_header = Alignment(horizontal='center')
align_header_v = Alignment(vertical='center', wrap_text=True)


# 拼接违规数据
def get_violation_info(item):
    title = item['Title']
    violation_content = re.sub('<.*?>', '', item['Content'])
    violation_cause = ''
    violation_title = ''
    violation_result = ''
    if re.search('违规处理', title):
        if re.search('涉[嫌及](.+?)，', violation_content):
            violation_cause = re.search('涉[嫌及](.+?)，', violation_content).group(1)
            violation_title = re.search(
                '违规(.*?)消息“(.*?)”', violation_content).group(2)
        else:
            violation_cause = re.search('发现此公众号(.+?)，', violation_content).group(1)
            violation_title = re.search(
                '违规(.*?)消息“(.*?)”', violation_content).group(2)
    elif re.search('功能屏蔽', title):
        if re.search('涉[嫌及](.+?)，', violation_content):
            violation_cause = re.search(
                '涉[嫌及](.+?)，', violation_content).group(1)
        elif re.search('您的帐号经查(.+?)，', violation_content):
            violation_cause = re.search(
                '您的帐号经查(.+?)，', violation_content).group(1)
        if re.search('违规内容：(.+?)如有异议', violation_content):
            violation_title = re.sub('&nbsp;', '', re.search(
                '违规内容：(.+?)如有异议', violation_content).group(1))
        elif re.search('流量主通过不正当方式制造虚假或无效曝光量、点击量', violation_content):
            violation_title = re.search(
                '流量主通过不正当方式制造虚假或无效曝光量、点击量', violation_content).group(0)
        features_by_date = {}
        features = re.findall('已屏蔽([^功能]+?)功能至([^,，]+)[，,]', violation_content)
        for feature in features:
            feature_name = feature[0]
            feature_date = feature[1]
            if feature_date in features_by_date:
                features_by_date[feature_date].append(feature_name)
            else:
                features_by_date[feature_date] = [feature_name]
        for feature_date, forbidden_features in features_by_date.items():
            violation_result += "{}: {}\n".format(
                feature_date, ','.join(forbidden_features))
    elif re.search('粉丝删除', title):
        violation_cause = re.search('所禁止的(.+?)，', violation_content).group(1)
        violation_title = re.sub('&nbsp;', '', re.search(
            '发起的"(.*?)"', violation_content).group(1))
        violation_result = re.search('已删除.+?粉丝数。', violation_content).group(0)
    elif re.search('责令处理', title):
        violation_title = re.search('图文消息“(.*?)”', violation_content).group(1)
        violation_result = re.search(
            '已被互联网信息内容主管部门责令删除', violation_content).group(0)
    return violation_cause, violation_title, violation_result


# 设置单元格宽度
def set_columns_width(sheet, columns_width):
    for index, width in enumerate(columns_width):
        sheet.column_dimensions[get_column_letter(index + 1)].width = width


# 拼接基本信息
def get_basic_data(b):
    return [b.get('charge'), b.get('nickname'), b.get('wx_id'), b.get('gh_id'),
            b.get('fans_src'), b.get('type'), b.get('gender')]


def set_border(rows):
    for row in rows:
        for cell in row:
            cell.border = border_normal


def set_styles(rows, fill=None, alignment=None):
    for row in rows:
        for cell in row:
            if fill:
                cell.fill = fill
            if alignment:
                cell.alignment = alignment


# 生成表格
class ReportGenerator:
    def __init__(self, library, date_to_report):
        """
        :param utils.AccountLibrary library:
        :param date_to_report:
        """
        self.date = date_to_report
        self.library = library
        self.gh_id = None

    # 读取基础信息
    def get_basic(self, gh_id):
        date = self.date
        if self.date == utils.get_today():
            date = utils.get_today()
        return utils.get_json_file(gh_id, date, 'basic.json')

    # 读取用户数据
    def get_user_counter(self, gh_id):
        date = self.date
        if self.date == utils.get_today():
            date = utils.get_yesterday()
        return utils.get_json_file(gh_id, date, 'user-counter.json')

    # 读取违规数据
    def get_violation_list(self, gh_id):
        return utils.get_json_file(gh_id, self.date, 'violation-list.json', data_type=list)

    def save_excel(self, workbook, name):
        filename = 'output/{} {}.xlsx'.format(self.date, name)
        try:
            workbook.save(filename)
            workbook.close()
        except PermissionError:
            print('无法写入{}，请检查是否在Excel中打开了文件，如有需要请另存为并关闭'.format(filename))

    def make_today_ad(self):
        os.makedirs('output', exist_ok=True)
        self.make_violation_data()

    def make_violation_data(self):
        workbook, sheet = utils.make_workbook()
        set_columns_width(
            sheet, [8, 20, 10, 20, 5, 8, 5, 12, 30, 30, 40, 8])
        sheet.append(['日期', utils.get_today()])
        sheet.append(['负责人', '名称', '微信号', '原始ID', '粉丝来源', '类型', '男/女', '累计关注',
                      '违规类型', '违规内容', '违规处理', '是否封禁'])
        row_index = 2
        for gh_id in self.library.get_account_list():
            b = self.get_basic(gh_id)
            u = self.get_user_counter(gh_id)
            v = self.get_violation_list(gh_id)
            if v:
                try:
                    violationlist_by_title = {}
                    for value in v:
                        if "审核不通过" in str(value):
                            continue
                        violation_cause, violation_title, violation_result = get_violation_info(
                            value)
                        if violation_title in violationlist_by_title:
                            if violation_result:
                                violationlist_by_title[violation_title] = [
                                    violation_cause, violationlist_by_title[violation_title][1] + violation_result]
                            else:
                                violationlist_by_title[violation_title] = [
                                    violationlist_by_title[violation_title][0],
                                    violationlist_by_title[violation_title][1] + violation_result]
                        else:
                            violationlist_by_title[violation_title] = [
                                violation_cause, violation_result]

                    for vio_title, vio_info in violationlist_by_title.items():
                        row_index += 1
                        sheet.append(get_basic_data(b) +
                                     [u.get('cumulate_user'), vio_info[0],
                                      vio_title, vio_info[1], '是' if vio_info[1] else '否'])
                except Exception as e:
                    print(e)
                    print(gh_id)
        sheet['A1'].fill = fill_date
        set_styles(sheet['A2:L2'], fill_main, align_header)
        set_styles(sheet['A2:L{}'.format(row_index)], alignment=align_header_v)
        set_border(sheet['A2:L{}'.format(row_index)])
        sheet.freeze_panes = 'I3'
        self.save_excel(workbook, '违规数据表格')


if __name__ == '__main__':
    collect.test_collect()
    reporter = ReportGenerator(
        utils.default_library(), utils.get_today())
    reporter.make_today_ad()
